package com.siyoumi.app.modules.lucky_num.service;

import com.siyoumi.app.entity.LnumNumSet;
import com.siyoumi.app.entity.SysStock;
import com.siyoumi.app.modules.fun.service.SvcFun;
import com.siyoumi.app.modules.lucky_num.vo.VaLnumNumSet;
import com.siyoumi.app.service.LnumNumSetService;
import com.siyoumi.app.service.SysStockService;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Data
@Slf4j
@Service
public class SvcLnumNumSet
        implements IWebService {
    static public SvcLnumNumSet getBean() {
        return XSpringContext.getBean(SvcLnumNumSet.class);
    }

    static public LnumNumSetService getApp() {
        return LnumNumSetService.getBean();
    }

    public LnumNumSet first(String groupId, String id) {
        LnumNumSet entity = getApp().first(id);
        if (entity == null) {
            return entity;
        }
        if (!entity.getLnset_group_id().equals(groupId)) {
            XValidator.err(20051, "分组ID不一致");
        }

        return entity;
    }

    /**
     * 是否有效
     *
     * @param entitySet
     * @param openid
     */
    public XReturn valid(LnumNumSet entitySet, String openid) {
        if (entitySet.getLnset_get_date_begin().isAfter(LocalDateTime.now())) {
            return XReturn.getR(20138, "未开始");
        }
        if (entitySet.getLnset_get_date_end().isBefore(LocalDateTime.now())) {
            return XReturn.getR(20137, "已结束");
        }

        if (XStr.hasAnyText(openid)) {
            Long count = SvcLNumGroup.getBean().numCount(entitySet.getLnset_group_id(), entitySet.getLnset_id());
            if (count >= entitySet.getLnset_user_get_max()) {
                return XReturn.getR(20149, "用户已领过");
            }

            SysStock entityLeft = SysStockService.getBean().getEntityBySrc(entitySet.getLnset_id(), false);
            if (entityLeft.getStock_count_left() <= 0) {
                return XReturn.getR(20150, "库存为0");
            }

            if (entitySet.getLnset_fun_enable() == 1) {
                Long leftFun = SvcFun.getBean().getFun(openid);
                if (leftFun < entitySet.getLnset_fun()) {
                    return XReturn.getR(20155, "用户积分不足");
                }
            }
        }


        return EnumSys.OK.getR();
    }

    public void editAfter(InputData inputData, XReturn r, String idSrc) {
        Map<String, Object> data = (Map<String, Object>) r.get("data");
        if (data == null) {
            data = new HashMap<>();
        }

        data.put("lnset_user_get_max", 0);
        data.put("lnset_fun_enable", 0);
        data.put("lnset_fun", 0);
        // 为了避免，错误修改，库存会赋到新值
        data.put("stock_count_use", 0);
        data.put("stock_count_left", 0);
        data.put("stock_count_left_old", 0);
        if (inputData.isAdminEdit()) {
            LnumNumSet entity = SvcLnumNumSet.getApp().first(idSrc);
            if (entity == null) {
                return;
            }
            data.putAll(entity.toMap());

            Map<String, Object> dataAppend = new LinkedHashMap<>();
//            dataAppend.put("id", entity.getKey());

            SysStock entityStock = SysStockService.getBean().getEntityBySrc(entity.getKey(), false);
            if (entityStock != null) {
                dataAppend.put("stock_count_use", entityStock.getStock_count_use());
                dataAppend.put("stock_count_left", entityStock.getStock_count_left());
                dataAppend.put("stock_count_left_old", entityStock.getStock_count_left());
            }
            //合并
            data.putAll(dataAppend);
        }
        r.setData("data", data);

        Map<String, Object> mapPageInfo = r.getData("page_info");
    }

    /**
     * 发奖配置-保存
     *
     * @param idSrc
     * @param vo
     */
    @SneakyThrows
    public void editSave(String idSrc, Object vo) {
        if (XStr.isNullOrEmpty(idSrc)) {
            XValidator.err(50081, "miss id_src");
        }
        VaLnumNumSet numSetVo = (VaLnumNumSet) vo;
        //发奖配置
        LnumNumSet entitySet = SvcLnumNumSet.getApp().first(idSrc);
        LnumNumSet entitySetUpdate = SvcLnumNumSet.getApp().loadEntity(XBean.toMap(numSetVo));
        if (entitySet == null) {
            entitySetUpdate.setLnset_x_id(XHttpContext.getX());
            entitySetUpdate.setLnset_id(idSrc);
        }
        SvcLnumNumSet.getApp().saveOrUpdatePassEqualField(entitySet, entitySetUpdate);

        //库存配置
        SysStock entityStock = SysStockService.getBean().getEntityBySrc(idSrc);
        if (entityStock == null) {
            entityStock = new SysStock();
            entityStock.setStock_x_id(XHttpContext.getX());
            entityStock.setStock_app_id("lucky_num");
            entityStock.setStock_id_src(idSrc);
            entityStock.setAutoID();
            SysStockService.getBean().save(entityStock);
        }
        //修改余量
        SysStockService.getBean().updateLeft(idSrc, numSetVo.getStock_count_left(), numSetVo.getStock_count_left_old());
    }


    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        getApp().delete(ids);

        return r;
    }
}
